package org.dreamfly.dreamalarm.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import org.dreamfly.dreamalarm.bean.Alarm;

import android.util.Log;

public class DreamAlarmDateFormat {
	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");

	/**
	 * 返回true 如果第二个时间比第一个晚
	 * 
	 * @param first
	 * @param second
	 * @return
	 */
	public static boolean judgeBigger(String first, String second) {
		try {
			Date first_time = dateFormat.parse(first);
			Date second_time = dateFormat.parse(second);
			return first_time.before(second_time);
		} catch (ParseException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		}
		return false;
	}

	/**
	 * 返回页面显示的时间
	 * 
	 * @param h
	 *            hour
	 * @param m
	 *            minute
	 * @return string h:m
	 */
	public static String formatTime(int h, int m) {
		String s="";
		s+= (h>=10)? h : "0"+h;
		s+=":";
		s+= (m>=10)? m : "0"+m;
		return s;
	}

	/**
	 * 设置时间转化为字符串 hour:minute
	 * 
	 * @param calendar
	 * @return
	 */
	public static String timeToString(Calendar calendar) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(calendar.get(Calendar.HOUR_OF_DAY));
		stringBuilder.append(":");
		stringBuilder.append(calendar.get(Calendar.MINUTE));
		return stringBuilder.toString();
	}

	/**
	 * hh:mm to hh:mm:ss
	 * @param s
	 * @return
	 */
	public static String stringToDBStringTime(String s){
		return s+":00";
	}
	
	/**
	 * 字符串化为当日Calendar
	 * 
	 * @param time
	 * @return 当字符串不是h：m格式时返回null
	 */
	public static Calendar stringToTime(String time) {
		StringTokenizer stringTokenizer = new StringTokenizer(time, ":");
		Calendar calendar = null;

		try {
			// 临时变量，用于保证错误时不实例化calendar
			int h = Integer.parseInt(stringTokenizer.nextToken());
			int m = Integer.parseInt(stringTokenizer.nextToken());

			calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, h);
			calendar.set(Calendar.MINUTE, m);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
		} catch (Exception e) {
			Log.e("org.dreamfly.dreamalarm.dateformat", "time error:"+time);
		}
		return calendar;
	}
	
	public static boolean laterThanNow(Calendar calendar){
		return (calendar.getTimeInMillis()<= System.currentTimeMillis())?false:true;
	}
	
	/**
	 * 获取当前是周几，
	 * 如果有当天并在之后，直接设置闹钟
	 * 其他情况，自增取余数看哪天响闹钟，然后增加天数*24*60*60*1000
	 * @param alarm
	 * @return 下次响铃时间
	 */
	public static Calendar getNextCalendar(Alarm alarm, boolean justNotToday){
		final int ONE_DAY_MILLIS=24*60*60*1000;
		Calendar calendar=alarm.getTimeDate();
		
		//不重复的情况
		if(alarm.getRepeat()==0){
			if(justNotToday || alarm.getTimeDate().getTimeInMillis() <= System.currentTimeMillis()){
				calendar.setTimeInMillis(calendar.getTimeInMillis()+ONE_DAY_MILLIS);
				return calendar;
			}
			return alarm.getTimeDate();
		}
		
		//numberMODByAlarmRepeatToPowTen:1-7 begin from tomorrow or today(比当前时间晚)
		//first +1：用户从明天开始， second +1:用于取余
		//注意sunday为1 monday为2
		int todayOfWeek=Calendar.getInstance().get(Calendar.DAY_OF_WEEK); //修正sunday
		if(todayOfWeek==Calendar.SUNDAY){
			todayOfWeek=7;
		}else{
			todayOfWeek--;
		}
		
		int numberMODByAlarmRepeatToPowTen=7-todayOfWeek+1;
		if(justNotToday || alarm.getTimeDate().getTimeInMillis() <= System.currentTimeMillis()){
			numberMODByAlarmRepeatToPowTen=numberMODChangeOneStep(numberMODByAlarmRepeatToPowTen);
			calendar.setTimeInMillis(calendar.getTimeInMillis()+ONE_DAY_MILLIS);
		}
		
		for(int i=0;;numberMODByAlarmRepeatToPowTen=numberMODChangeOneStep(numberMODByAlarmRepeatToPowTen),i++){
			if(isAlarmRepeated(alarm.getRepeat(),numberMODByAlarmRepeatToPowTen)){
				Calendar calendarReturn=Calendar.getInstance();
				calendarReturn.setTimeInMillis(i*ONE_DAY_MILLIS+calendar.getTimeInMillis());
				return calendarReturn;
			}
		}
	}
	
	/**
	 * 判断给定的日期是否需要响铃
	 * @param alarmRepeat
	 * @param numberMODByAlarmRepeatToPowTen 暂定为x，用法： alarmRepeat%(10^x)/10^(x-1)判断是否为Alarm.REPEAT_TRUE
	 * @return
	 */
	private static boolean isAlarmRepeated(int alarmRepeat, int numberMODByAlarmRepeatToPowTen){
		if(((alarmRepeat%((int)Math.pow(10, numberMODByAlarmRepeatToPowTen))))/
				(int)Math.pow(10, numberMODByAlarmRepeatToPowTen-1)
				==Alarm.REPEAT_TRUE){
			return true;
		}
		return false;
	}
	
	private static int numberMODChangeOneStep(int numberMODByAlarmRepeatToPowTen){
		numberMODByAlarmRepeatToPowTen=numberMODByAlarmRepeatToPowTen-1;
		if(numberMODByAlarmRepeatToPowTen==0){
			return 7;
		}
		return numberMODByAlarmRepeatToPowTen;
	}
}
